import type { RouteRecordRaw } from "vue-router";
import { constantRoutes } from "@/router";
import { store } from "@/store";
import router from "@/router";

import { type RouteVO } from "@/api/system/menu";

const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");

export const usePermissionStore = defineStore("permission", () => {
  // 所有路由，包括静态和动态路由
  const routes = ref<RouteRecordRaw[]>([]);
  // 混合模式左侧菜单
  const mixLeftMenus = ref<RouteRecordRaw[]>([]);
  // 路由是否已加载
  const isRoutesLoaded = ref(false);

  /**
   * 生成动态路由
   */
  // function generateRoutes() {
  //   return new Promise<RouteRecordRaw[]>((resolve, reject) => {
  //     MenuAPI.getRoutes()
  //       .then((data) => {
  //         let getUserInfo = JSON.parse(sessionStorage.getItem("USER_INFO") || "{}");

  //         interface MenuItem {
  //           id: number;
  //           moduleName: string;
  //           modulePath: string;
  //           parentId: number;
  //           perms: number;
  //           sort: string;
  //           sysModuleList: MenuItem[];
  //         }

  //         interface RouteItem {
  //           path: string;
  //           component: string;
  //           redirect?: string;
  //           name: string;
  //           meta: {
  //             title: string;
  //             icon: string;
  //             hidden: boolean;
  //             alwaysShow: boolean;
  //             params: any;
  //           };
  //           children: RouteVO[];
  //         }

  //         function filterRoutesByMenu(menuList: MenuItem[], data: RouteItem[]): RouteItem[] {
  //           return menuList
  //             .map((menu) => {
  //               const route = data.find((d) => d.path === `/${menu.modulePath}`);
  //               if (!route) return null;

  //               const newRoute: RouteItem = {
  //                 ...route,
  //                 children: menu.sysModuleList
  //                   .map((subMenu) => {
  //                     const childRoute = route.children?.find(
  //                       (child) => child.path === subMenu.modulePath.split("/").pop()
  //                     );
  //                     return childRoute ? { ...childRoute } : null;
  //                   })
  //                   .filter((child): child is RouteVO => child !== null), // 过滤掉 null
  //               };

  //               // 确保 children 始终是一个数组
  //               newRoute.children = newRoute.children || [];

  //               return newRoute;
  //             })
  //             .filter((route): route is RouteItem => route !== null); // 过滤掉 null
  //         }

  //         const newData = filterRoutesByMenu(getUserInfo.menuList, data as RouteItem[]);
  //         console.log("用户信息", newData);

  //         const dynamicRoutes = transformRoutes(newData); //如果需要路由的话
  //         // const dynamicRoutes = transformRoutes(data);
  //         routes.value = constantRoutes.concat(dynamicRoutes);
  //         isRoutesLoaded.value = true;
  //         resolve(dynamicRoutes);
  //       })
  //       .catch((error) => {
  //         reject(error);
  //       });
  //   });
  // }

  function generateRoutes() {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      try {
        let data: RouteItem[] = [
          {
            path: "/order",
            component: "Layout",
            redirect: "/order/master",
            name: "/order",
            meta: {
              title: "订单管理",
              icon: "el-icon-shopping-bag",
              hidden: false,
              alwaysShow: true,
              params: null,
            },
            children: [
              {
                path: "master",
                component: "order/master/index",
                name: "Master",
                meta: {
                  title: "销售订单维护作业",
                  icon: "el-icon-document-checked",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "orderReturn",
                component: "order/orderReturn/index",
                name: "OrderReturn",
                meta: {
                  title: "销售订单退货",
                  icon: "el-icon-refresh-left",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
            ],
          },
          {
            path: "/purchase",
            component: "Layout",
            redirect: "/purchase/manage",
            name: "/purchase",
            meta: {
              title: "采购管理",
              icon: "el-icon-Postcard", // 采购卡图标
              hidden: false,
              alwaysShow: true,
              params: null,
            },
            children: [
              {
                path: "manage",
                component: "purchase/manage/index",
                name: "Manage",
                meta: {
                  title: "采购订单维护作业",
                  icon: "el-icon-shopping-cart-full", // 购物车满图标
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
            ],
          },
          {
            path: "/priceMaintenance",
            component: "Layout",
            name: "/priceMaintenance",
            meta: {
              title: "基准价格维护",
              icon: "el-icon-price-tag", // 价格标签图标
              hidden: false,
              alwaysShow: true,
              params: null,
            },
            children: [
              {
                path: "productPrice",
                component: "priceMaintenance/productPrice/index",
                name: "ProductPrice",
                meta: {
                  title: "产品价格维护",
                  icon: "el-icon-box", // 产品包装图标
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "rawMaterialPrice",
                component: "priceMaintenance/rawMaterialPrice/index",
                name: "RawMaterialPrice",
                meta: {
                  title: "原材料价格维护",
                  icon: "el-icon-cpu", // 原料组件图标
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
            ],
          },
          {
            path: "/planManage",
            component: "Layout",
            redirect: "/planManage",
            name: "/PlanManage",
            meta: {
              title: "计划管理",
              icon: "el-icon-alarm-clock", // 计划时钟图标
              hidden: false,
              alwaysShow: true,
              params: null,
            },
            children: [
              {
                path: "planOrderManage",
                component: "planManage/planOrderManage/index",
                name: "PlanOrderManage",
                meta: {
                  title: "生产计划管理",
                  icon: "el-icon-set-up", // 生产设置
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "planMrp",
                component: "planManage/planMrp/index",
                name: "PlanMrp",
                meta: {
                  title: "MRP",
                  icon: "el-icon-data-analysis", // 数据分析
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "planPurchas",
                component: "planManage/planPurchas/index",
                name: "PlanPurchas",
                meta: {
                  title: "采购计划维护",
                  icon: "el-icon-Van", // 货车运输
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "planDeliverGoods",
                component: "planManage/planDeliverGoods/index",
                name: "PlanDeliverGoods",
                meta: {
                  title: "送货计划维护",
                  icon: "el-icon-PictureRounded", // 移动配送
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
            ],
          },

          {
            path: "/prodManage",
            component: "Layout",
            redirect: "/prodManage/prodOrderManage",
            name: "/ProdManage",
            meta: {
              title: "生产管理",
              icon: "el-icon-Box", // 工厂图标
              hidden: false,
              alwaysShow: true,
              params: null,
            },
            children: [
              {
                path: "prodOrderManage",
                component: "prodManage/prodOrderManage/index",
                name: "ProdOrderManage",
                meta: {
                  title: "生产单管理",
                  icon: "el-icon-ship", // 生产流水线
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "materialQuery",
                component: "prodManage/materialQuery/index",
                name: "MaterialQuery",
                meta: {
                  title: "用料查询",
                  icon: "el-icon-More",
                  hidden: true,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "scheduling",
                component: "prodManage/scheduling/index",
                name: "Scheduling",
                meta: {
                  title: "工作排班作业",
                  icon: "el-icon-user", // 人员排班
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              // {
              //   path: "deviceReady",
              //   component: "prodManage/deviceReady/index",
              //   name: "DeviceReady",
              //   meta: {
              //     title: "设备准备查询",
              //     icon: "el-icon-HelpFilled",
              //     hidden: false,
              //     keepAlive: false,
              //     alwaysShow: false,
              //     params: null,
              //   },
              //   children: [],
              // },
              {
                path: "stockPreparation",
                component: "prodManage/stockPreparation/index",
                name: "StockPreparation",
                meta: {
                  title: "产前备料情况查询",
                  icon: "el-icon-collection-tag", // 物料准备
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "productLabel",
                component: "prodManage/productLabel/index",
                name: "ProductLabel",
                meta: {
                  title: "产品标签打印作业",
                  icon: "el-icon-printer", // 打印图标
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
            ],
          },
          {
            path: "/warehouseManage",
            component: "Layout",
            name: "/warehouseManage",
            meta: {
              title: "仓库管理",
              icon: "el-icon-house", // 仓库图标
              hidden: false,
              alwaysShow: true,
              params: null,
            },
            children: [
              {
                path: "wareArchives",
                component: "warehouseManage/wareArchives/index",
                name: "WareArchives",
                meta: {
                  title: "仓库档案",
                  icon: "el-icon-files", // 档案文件
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "stockCheck",
                component: "warehouseManage/stockCheck/index",
                name: "StockCheck",
                meta: {
                  title: "库存查询-仓库",
                  icon: "el-icon-search",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "stockProduct",
                component: "warehouseManage/stockProduct/index",
                name: "StockProduct",
                meta: {
                  title: "库存查询-产品",
                  icon: "el-icon-box",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "stockOut",
                component: "warehouseManage/stockOut/index",
                name: "StockOut",
                meta: {
                  title: "出库资料维护",
                  icon: "el-icon-upload",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "stockIn",
                component: "warehouseManage/stockIn/index",
                name: "StockIn",
                meta: {
                  title: "入库资料维护",
                  icon: "el-icon-download",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              // {
              //   path: "rawMaterial",
              //   component: "warehouseManage/rawMaterial/index",
              //   name: "RawMaterial",
              //   meta: {
              //     title: "原材料库维护",
              //     icon: "el-icon-Remove",
              //     hidden: false,
              //     keepAlive: true,
              //     alwaysShow: false,
              //     params: null,
              //   },
              //   children: [],
              // },
              {
                path: "inventory",
                component: "warehouseManage/inventory/index",
                name: "Inventory",
                meta: {
                  title: "移库作业",
                  icon: "el-icon-sort",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },

              {
                path: "movingWork",
                component: "warehouseManage/movingWork/index",
                name: "MovingWork",
                meta: {
                  title: "盘点作业",
                  icon: "el-icon-check",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              // {
              //   path: "rawMaterialStock",
              //   component: "warehouseManage/rawMaterialStock/index",
              //   name: "RawMaterialStock",
              //   meta: {
              //     title: "原材料库存查询",
              //     icon: "el-icon-Tickets",
              //     hidden: false,
              //     keepAlive: true,
              //     alwaysShow: false,
              //     params: null,
              //   },
              //   children: [],
              // },
              // {
              //   path: "productMaintenance",
              //   component: "warehouseManage/productMaintenance/index",
              //   name: "ProductMaintenance",
              //   meta: {
              //     title: "产品库维护",
              //     icon: "el-icon-Rank",
              //     hidden: false,
              //     keepAlive: true,
              //     alwaysShow: false,
              //     params: null,
              //   },
              //   children: [],
              // },
              // {
              //   path: "stockInfo",
              //   component: "warehouseManage/stockInfo/index",
              //   name: "StockInfo",
              //   meta: {
              //     title: "仓库基础信息",
              //     icon: "el-icon-Fold",
              //     hidden: false,
              //     keepAlive: true,
              //     alwaysShow: false,
              //     params: null,
              //   },
              //   children: [],
              // },
              // {
              //   path: "storageDetails",
              //   component: "warehouseManage/storageDetails/index",
              //   name: "StorageDetails",
              //   meta: {
              //     title: "库储明细",
              //     icon: "el-icon-DocumentAdd",
              //     hidden: false,
              //     keepAlive: true,
              //     alwaysShow: false,
              //     params: null,
              //   },
              //   children: [],
              // },
            ],
          },

          {
            path: "/LogisticsManagement",
            component: "Layout",
            name: "LogisticsManagement",
            meta: {
              title: "物流管理",
              icon: "el-icon-Van",
              hidden: false,
              alwaysShow: true,
              params: null,
            },
            children: [
              //车辆监控设备绑定
              {
                path: "vehicleMonitoring",
                component: "LogisticsManagement/vehicleMonitoring/index",
                name: "VehicleMonitoring",
                meta: {
                  title: "车辆监控设备绑定",
                  icon: "el-icon-monitor",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },

              {
                path: "vehicleMonitoringData",
                component: "LogisticsManagement/vehicleMonitoringData/index",
                name: "VehicleMonitoringData",
                meta: {
                  title: "车辆监控数据查看",
                  icon: "el-icon-data-line",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "vehicleScheduling",
                component: "LogisticsManagement/vehicleScheduling/index",
                name: "VehicleScheduling",
                meta: {
                  title: "车辆调度查询",
                  icon: "el-icon-map-location",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "deliveryOrderMaintenance",
                component: "LogisticsManagement/deliveryOrderMaintenance/index",
                name: "DeliveryOrderMaintenance",
                meta: {
                  title: "送货单维护",
                  icon: "el-icon-DocumentAdd",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "loadingParkingSpaceInquiry",
                component: "LogisticsManagement/loadingParkingSpaceInquiry/index",
                name: "LoadingParkingSpaceInquiry",
                meta: {
                  title: "装车车位信息查询",
                  icon: "el-icon-AddLocation",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "unloadingParkingSpaceInquiry",
                component: "LogisticsManagement/unloadingParkingSpaceInquiry/index",
                name: "UnloadingParkingSpaceInquiry",
                meta: {
                  title: "卸车车位信息查询",
                  icon: "el-icon-DeleteLocation",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
            ],
          },
          {
            path: "/cusManagement",
            component: "Layout",
            redirect: "/cusManagement",
            name: "/CusManagement",
            meta: {
              title: "客户管理",
              icon: "el-icon-UserFilled",
              hidden: false,
              alwaysShow: true,
              params: null,
            },
            children: [
              {
                path: "cusInfo",
                component: "cusManagement/cusInfo/index",
                name: "CusInfo",
                meta: {
                  title: "客户信息维护",
                  icon: "el-icon-Notebook",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "conManagement",
                component: "cusManagement/conManagement/index",
                name: "ConManagement",
                meta: {
                  title: "客户合同管理",
                  icon: "el-icon-Document",
                  hidden: false,
                  keepAlive: false,

                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
            ],
          },
          {
            path: "/suppManagement",
            component: "Layout",
            redirect: "/suppManagement",
            name: "/SuppManagement",
            meta: {
              title: "供应商管理",
              icon: "el-icon-Cherry",
              hidden: false,
              alwaysShow: true,
              params: null,
            },
            children: [
              {
                path: "suppInfo",
                component: "suppManagement/suppInfo/index",
                name: "SuppInfo",
                meta: {
                  title: "供应商信息维护",
                  icon: "el-icon-Memo",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "suppConManagement",
                component: "suppManagement/suppConManagement/index",
                name: "SuppConManagement",
                meta: {
                  title: "供应商合同管理",
                  icon: "el-icon-Document",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
            ],
          },
          {
            path: "/product",
            component: "Layout",
            name: "/product",
            meta: {
              title: "产品管理",
              icon: "el-icon-FolderRemove",
              hidden: false,
              alwaysShow: true,
              params: null,
            },
            children: [
              {
                path: "productCategory",
                component: "product/productCategory/index",
                name: "ProductCategory",
                meta: {
                  title: "产品类别维护",
                  icon: "el-icon-CopyDocument",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "productInfo",
                component: "product/productInfo/index",
                name: "ProductInfo",
                meta: {
                  title: "产品资料维护",
                  icon: "el-icon-Reading",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "productBom",
                component: "product/productBom/index",
                name: "ProductBom",
                meta: {
                  title: "产品BOM维护",
                  icon: "el-icon-Present",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },

              {
                path: "basicProcess",
                component: "product/basicProcess/index",
                name: "BasicProcess",
                meta: {
                  title: "基础工序维护",
                  icon: "el-icon-Cpu",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "processCard",
                component: "product/processCard/index",
                name: "ProcessCard",
                meta: {
                  title: "工艺卡数据维护",
                  icon: "el-icon-Film",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
            ],
          },
          // {
          //   path: "/productTraceability",
          //   component: "Layout",
          //   name: "productTraceability",
          //   meta: {
          //     title: "产品溯源",
          //     icon: "el-icon-Mouse",
          //     hidden: false,
          //     alwaysShow: false,
          //     params: null,
          //   },
          //   children: [],
          // },

          {
            path: "/quality",
            component: "Layout",
            name: "/quality",
            meta: {
              title: "质量管理",
              icon: "el-icon-PieChart",
              hidden: false,
              alwaysShow: true,
              params: null,
            },
            children: [
              {
                path: "rawQuality",
                component: "quality/rawQuality/index",
                name: "RawQuality",
                meta: {
                  title: "原材料质量管理",
                  icon: "el-icon-Apple",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "rawLaboratoryManagement",
                component: "quality/rawLaboratoryManagement/index",
                name: "rawLaboratoryManagement",
                meta: {
                  title: "原材料化验管理",
                  icon: "el-icon-MessageBox",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "productQuality",
                component: "quality/productQuality/index",
                name: "ProductQuality",
                meta: {
                  title: "产品质量管理",
                  icon: "el-icon-Watch",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "laboratoryManagement",
                component: "quality/laboratoryManagement/index",
                name: "LaboratoryManagement",
                meta: {
                  title: "产品化验管理",
                  icon: "el-icon-Box",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "productReview",
                component: "quality/productReview/index",
                name: "ProductReview",
                meta: {
                  title: "产品质量追溯",
                  icon: "el-icon-Paperclip",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "qualityControl",
                component: "quality/qualityControl/index",
                name: "QualityControl",
                meta: {
                  title: "质量控制作业",
                  icon: "el-icon-Compass",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "/productTraceability",
                component: "productTraceability/index",
                name: "ProductTraceability",
                meta: {
                  title: "产品溯源",
                  icon: "el-icon-Sell",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
            ],
          },

          {
            path: "/assetManagement",
            component: "Layout",
            name: "AssetManagement",
            meta: {
              title: "资产管理",
              icon: "el-icon-Iphone",
              hidden: false,
              alwaysShow: true,
              params: null,
            },
            children: [
              {
                path: "basketHandling",
                component: "assetManagement/basketHandling/index",
                name: "BasketHandling",
                meta: {
                  title: "资产管理",
                  icon: "el-icon-Iphone",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },

              {
                path: "basketManagement",
                component: "assetManagement/basketManagement/index",
                name: "BasketManagement",
                meta: {
                  title: "筐管理",
                  icon: "el-icon-MessageBox",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
            ],
          },
          {
            path: "/equipmentManagement",
            component: "Layout",
            name: "/equipmentManagement",
            meta: {
              title: "设备管理",
              icon: "el-icon-TakeawayBox",
              hidden: false,
              alwaysShow: false,
              params: null,
            },
            children: [
              {
                path: "equipmentInfo",
                component: "equipmentManagement/equipmentInfo/index",
                name: "EquipmentInfo",
                meta: {
                  title: "设备基础数据维护",
                  icon: "el-icon-Flag",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
            ],
          },
          // {
          //   path: "/productTraceability",
          //   component: "Layout",
          //   name: "/productTraceability",
          //   meta: {
          //     title: "产品溯源",
          //     icon: "el-icon-Mouse",
          //     hidden: false,
          //     alwaysShow: false,
          //     params: null,
          //   },
          //   children: [],
          // },

          // {
          //   path: "/file",
          //   component: "Layout",
          //   name: "/file",
          //   meta: {
          //     title: "文件管理",
          //     icon: "el-icon-Sunny",
          //     hidden: false,
          //     alwaysShow: false,
          //     params: null,
          //   },
          //   children: [
          //     {
          //       path: "fileManagement",
          //       component: "file/fileManagement/index",
          //       name: "fileManagement",
          //       meta: {
          //         title: "一般文件管理",
          //         icon: "el-icon-Shop",
          //         hidden: false,
          //         keepAlive: false,
          //         alwaysShow: false,
          //         params: null,
          //       },
          //       children: [],
          //     },
          //   ],
          // },
          {
            path: "/shopping",
            component: "shopping/index",
            name: "shopping",
            meta: {
              title: "商城",
              icon: "el-icon-ShoppingCart",
              hidden: true,
              alwaysShow: false,
              params: null,
            },
            children: [
              {
                path: "/",
                component: "shopping/index",
                name: "Shopping",
                meta: {
                  title: "商城",
                  icon: "el-icon-ShoppingCart",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
            ],
          },

          {
            path: "/farmerInformation",
            component: "Layout",
            name: "farmerInformation",
            meta: {
              title: "农户信息管理",
              icon: "el-icon-Mouse",
              hidden: false,
              alwaysShow: false,
              params: null,
            },
            children: [
              {
                path: "farmerInformation",
                component: "farmerInformation/index",
                name: "FarmerInformations",
                meta: {
                  title: "农户信息管理",
                  icon: "el-icon-ElemeFilled",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
            ],
          },

          {
            path: "/statement",
            component: "Layout",
            name: "/statement",
            meta: {
              title: "报表",
              icon: "el-icon-MostlyCloudy",
              hidden: false,
              alwaysShow: false,
              params: null,
            },
            children: [
              {
                path: "salesOrder",
                component: "statement/salesOrder/index",
                name: "SalesOrder",
                meta: {
                  title: "销售订单统计",
                  icon: "el-icon-Shop",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "salesOrderProduct",
                component: "statement/salesOrderProduct/index",
                name: "SalesOrderProduct",
                meta: {
                  title: "销售订单产品统计",
                  icon: "el-icon-Shop",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "purchaseOrder",
                component: "statement/purchaseOrder/index",
                name: "PurchaseOrder",
                meta: {
                  title: "采购订单统计",
                  icon: "el-icon-Shop",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "purchaseOrderProduct",
                component: "statement/purchaseOrderProduct/index",
                name: "PurchaseOrderProduct",
                meta: {
                  title: "采购订单产品统计",
                  icon: "el-icon-Shop",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "customerStatistics",
                component: "statement/customerStatistics/index",
                name: "CustomerStatistics",
                meta: {
                  title: "客户统计",
                  icon: "el-icon-Shop",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "supplierStatistics",
                component: "statement/supplierStatistics/index",
                name: "SupplierStatistics",
                meta: {
                  title: "供应商统计",
                  icon: "el-icon-Shop",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "storageReport",
                component: "statement/storageReport/index",
                name: "StorageReport",
                meta: {
                  title: "储位报表",
                  icon: "el-icon-Shop",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "inventoryReport",
                component: "statement/inventoryReport/index",
                name: "InventoryReport",
                meta: {
                  title: "盘库报表",
                  icon: "el-icon-Shop",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "productionOrder",
                component: "statement/productionOrder/index",
                name: "ProductionOrder",
                meta: {
                  title: "生产单报表",
                  icon: "el-icon-Shop",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "priceOrder",
                component: "statement/priceOrder/index",
                name: "PriceOrder",
                meta: {
                  title: "产品价格趋势报表",
                  icon: "el-icon-Shop",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "quantityOrder",
                component: "statement/quantityOrder/index",
                name: "QuantityOrder",
                meta: {
                  title: "需求量报表",
                  icon: "el-icon-Shop",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
            ],
          },
          {
            path: "/largeScreen",
            component: "/",
            redirect: "/largeScreen",
            name: "/largeScreen",
            meta: {
              title: "可视化大屏",
              icon: "el-icon-Fries",
              hidden: false,
              alwaysShow: true,
              params: null,
            },
            children: [
              {
                path: "productionBoard",
                component: "largeScreen/productionBoard/index",
                name: "ProductionBoard",
                meta: {
                  title: "产线前看板",
                  icon: "el-icon-Folder",
                  hidden: false,
                  keepAlive: false,
                  hiddenBar: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "external",
                component: "largeScreen/external/index",
                name: "External",
                meta: {
                  title: "对外展示综合看板",
                  icon: "el-icon-Folder",
                  hidden: false,
                  keepAlive: false,
                  hiddenBar: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "godown",
                component: "largeScreen/godown/index",
                name: "Godown",
                meta: {
                  title: "仓库数据看板",
                  icon: "el-icon-Tickets",
                  hidden: true,
                  keepAlive: true,
                  hiddenBar: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "productionLine",
                component: "largeScreen/productionLine/index",
                name: "ProductionLine",
                meta: {
                  title: "产线缓存可视化大屏",
                  icon: "el-icon-Film",
                  hidden: true,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "cleanVegetable",
                component: "largeScreen/cleanVegetable/index",
                name: "CleanVegetable",
                meta: {
                  title: "净菜生产可视化大屏",
                  icon: "el-icon-School",
                  hidden: true,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "device",
                component: "largeScreen/device/index",
                name: "Device",
                meta: {
                  title: "设备动态可视化大屏",
                  icon: "el-icon-Place",
                  hidden: true,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "cleanFrame",
                component: "largeScreen/cleanFrame/index",
                name: "CleanFrame",
                meta: {
                  title: "净框需求可视化大屏",
                  icon: "el-icon-School",
                  hidden: true,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "cleanVegetableOne",
                component: "largeScreen/cleanVegetableOne/index",
                name: "CleanVegetableOne",
                meta: {
                  title: "净菜生产可视化大屏2",
                  icon: "el-icon-Pear",
                  hidden: true,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "cleanVegetableTwo",
                component: "largeScreen/cleanVegetableTwo/index",
                name: "CleanVegetableTwo",
                meta: {
                  title: "净菜生产可视化大屏3",
                  icon: "el-icon-Watermelon",
                  hidden: true,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "cleanVegetableThree",
                component: "largeScreen/cleanVegetableThree/index",
                name: "CleanVegetableThree",
                meta: {
                  title: "净菜生产可视化大屏4",
                  icon: "el-icon-Van",
                  hidden: true,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "cleanVegetableFour",
                component: "largeScreen/cleanVegetableFour/index",
                name: "CleanVegetableFour",
                meta: {
                  title: "净菜生产可视化大屏5",
                  icon: "el-icon-Bowl",
                  hidden: true,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "drain",
                component: "largeScreen/drain/index",
                name: "Drain",
                meta: {
                  title: "沥水间动态可视化大屏",
                  icon: "el-icon-Orange",
                  hidden: true,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
            ],
          },
          {
            path: "/basicData",
            component: "Layout",
            name: "/basicData",
            meta: {
              title: "基础数据",
              icon: "el-icon-MostlyCloudy",
              hidden: false,
              alwaysShow: false,
              params: null,
            },
            children: [
              {
                path: "organizational",
                component: "basicData/organizational/index",
                name: "Organizational",
                meta: {
                  title: "组织结构查询",
                  icon: "el-icon-Shop",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "employeeInfo",
                component: "basicData/employeeInfo/index",
                name: "EmployeeInfo",
                meta: {
                  title: "员工资料查询",
                  icon: "el-icon-Sunrise",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },

              {
                path: "constant",
                component: "basicData/constant/index",
                name: "Constant",
                meta: {
                  title: "常量查询",
                  icon: "el-icon-ElemeFilled",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              // {
              //   path: "farmerInformation",
              //   component: "basicData/farmerInformation/index",
              //   name: "FarmerInformation",
              //   meta: {
              //     title: "农户信息管理",
              //     icon: "el-icon-Sell",
              //     hidden: false,
              //     keepAlive: false,
              //     alwaysShow: false,
              //     params: null,
              //   },
              //   children: [],
              // },
            ],
          },
          {
            path: "/system",
            component: "Layout",
            redirect: "/system/user",
            name: "/system",
            meta: {
              title: "系统管理",
              icon: "el-icon-setting",
              hidden: false,
              alwaysShow: true,
              params: null,
            },
            children: [
              {
                path: "user",
                component: "system/user/index",
                name: "User",
                meta: {
                  title: "用户管理",
                  icon: "el-icon-user",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "role",
                component: "system/role/index",
                name: "Role",
                meta: {
                  title: "角色管理",
                  icon: "el-icon-Lock",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "logList",
                component: "system/logList/index",
                name: "LogList",
                meta: {
                  title: "日志管理",
                  icon: "el-icon-PieChart",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "message",
                component: "system/message/index",
                name: "Message",
                meta: {
                  title: "消息管理",
                  icon: "el-icon-Message",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
              {
                path: "myMessage",
                component: "system/message/myMessage/index",
                name: "MyMessage",
                meta: {
                  title: "我的消息",
                  icon: "el-icon-ChatDotRound",
                  hidden: false,
                  keepAlive: false,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },

              {
                path: "messageConfig",
                component: "system/message/config/index",
                name: "MessageConfig",
                meta: {
                  title: "消息配置",
                  icon: "el-icon-Setting",
                  hidden: false,
                  keepAlive: true,
                  alwaysShow: false,
                  params: null,
                },
                children: [],
              },
            ],
          },
        ];
        let getUserInfo = JSON.parse(sessionStorage.getItem("USER_INFO") || "{}");

        interface MenuItem {
          id: number;
          moduleName: string;
          modulePath: string;
          parentId: number;
          perms: number;
          sort: string;
          sysModuleList: MenuItem[];
        }

        interface RouteItem {
          path: string;
          component: string;
          redirect?: string;
          name: string;
          meta: {
            title: string;
            icon: string;
            hidden: boolean;
            alwaysShow: boolean;
            params: any;
            keepAlive?: boolean;
          };
          children: RouteVO[];
        }

        function filterRoutesByMenu(menuList: MenuItem[], data: RouteItem[]): RouteItem[] {
          return menuList
            .map((menu) => {
              const route = data.find((d) => d.path === `/${menu.modulePath}`);
              if (!route) return null;

              const newRoute: RouteItem = {
                ...route,
                children: menu.sysModuleList
                  .map((subMenu) => {
                    const childRoute = route.children?.find(
                      (child) => child.path === subMenu.modulePath.split("/").pop()
                    );
                    return childRoute ? { ...childRoute } : null;
                  })
                  .filter((child): child is RouteItem => child !== null), // 过滤掉 null
              };

              // 确保 children 始终是一个数组
              newRoute.children = newRoute.children || [];

              return newRoute;
            })
            .filter((route): route is RouteItem => route !== null); // 过滤掉 null
        }

        const newData = filterRoutesByMenu(getUserInfo.menuList, data as RouteItem[]);
        console.log("用户信息", newData);

        const dynamicRoutes = transformRoutes(newData); // 如果需要路由的话
        // const dynamicRoutes = transformRoutes(data); // 如果需要路由的话

        // const dynamicRoutes = transformRoutes(hardCodedData);
        routes.value = constantRoutes.concat(dynamicRoutes);
        isRoutesLoaded.value = true;
        resolve(dynamicRoutes);
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 混合模式菜单下根据顶部菜单路径设置左侧菜单
   *
   * @param topMenuPath - 顶部菜单路径
   */
  const setMixLeftMenus = (topMenuPath: string) => {
    const matchedItem = routes.value.find((item) => item.path === topMenuPath);
    if (matchedItem && matchedItem.children) {
      mixLeftMenus.value = matchedItem.children;
    }
  };

  /**
   * 重置路由
   */
  const resetRouter = () => {
    // 删除动态路由，保留静态路由
    routes.value.forEach((route) => {
      if (route.name && !constantRoutes.find((r) => r.name === route.name)) {
        // 从 router 实例中移除动态路由
        router.removeRoute(route.name);
      }
    });

    routes.value = [];
    mixLeftMenus.value = [];
    isRoutesLoaded.value = false;
  };

  return {
    routes,
    generateRoutes,
    mixLeftMenus,
    setMixLeftMenus,
    isRoutesLoaded,
    resetRouter,
  };
});

/**
 * 转换路由数据为组件
 */
const transformRoutes = (routes: RouteVO[]) => {
  const asyncRoutes: RouteRecordRaw[] = [];
  routes.forEach((route) => {
    const tmpRoute = { ...route } as RouteRecordRaw;
    // 顶级目录，替换为 Layout 组件
    if (tmpRoute.component?.toString() == "Layout") {
      tmpRoute.component = Layout;
    } else {
      // 其他菜单，根据组件路径动态加载组件
      const component = modules[`../../views/${tmpRoute.component}.vue`];
      if (component) {
        tmpRoute.component = component;
      } else {
        tmpRoute.component = modules["../../views/error-page/404.vue"];
      }
    }

    if (tmpRoute.children) {
      tmpRoute.children = transformRoutes(route?.children);
    }

    asyncRoutes.push(tmpRoute);
  });

  return asyncRoutes;
};

/**
 * 在组件外使用 Pinia store 实例 @see https://pinia.vuejs.org/core-concepts/outside-component-usage.html
 */
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
